package com.egghiro.j2se.game.sace.model.actor.player;

import com.egghiro.framework.j2se.game.core.SMath;
import com.egghiro.framework.j2se.game.core.model.actor.Sprite;
import com.egghiro.framework.j2se.game.core.view.SImage;
import com.egghiro.framework.j2se.game.core.view.canvas.SGraphics;
import com.egghiro.framework.j2se.game.model.shape.SVector2D;
import com.egghiro.framework.j2se.game.utils.PropertyUtils;
import com.egghiro.j2se.game.sace.param.SACEConst;

public class FloatTail extends Sprite {
    private static final SImage IMG = SImage.createImage(PropertyUtils.getAIMPropertyValue(SACEConst.AIM_P_DIR,
            SACEConst.AIM_P_Key_IMG_FLOAT_TAIL));
    private static final int SPACE = -5;
    private static final double DIS_SPD_RATE = 0.4;
    private static final int MIN_SPEED = 2;

    private Sprite prev;
    private SVector2D moveVector;

    public FloatTail(Sprite prev) {
        super(IMG, IMG.getWidth(), IMG.getHeight());
        // TODO Auto-generated constructor stub
        this.prev = prev;
        this.defineReferencePixel(getWidth() / 2, -SPACE);
        this.moveVector = new SVector2D();
        telport();
        // System.out.println(prev.getHeight() + "  " + prev.getRefY());
    }

    public void act(double prevDx, double prevDy) {

        moveVector.setX(getDelaydDxy(prev.get2DX(), this.get2DX(), prevDx));
        moveVector.setY(prevDy);

        act();
    }

    private double getDelaydDxy(int prevCollidePointXorY, int thisCollidePointXorY, double prevDxy) {
        int disXorY = prevCollidePointXorY - thisCollidePointXorY;

        double dXorY = disXorY * DIS_SPD_RATE;

        if (dXorY > 0 && dXorY < MIN_SPEED) {
            dXorY = SMath.min(disXorY, MIN_SPEED);
        } else if (dXorY > -MIN_SPEED && dXorY < 0) {
            dXorY = SMath.max(disXorY, -MIN_SPEED);
        }

        // 保證尾翼的速度不會超過本體。否則可能會出現尾翼在最远位置的附近“震動”的現象
        if (prevDxy != 0) {
            if (SMath.abs(dXorY) > SMath.abs(prevDxy)) {
                dXorY = prevDxy;
            }
        }

        return dXorY;

    }

    @Override
    public void act() {
        this.move((int) moveVector.getX(), (int) moveVector.getY());
    }

    @Override
    public void paint(SGraphics g) {
        g.drawImage(sImage.getBufferedImage(), getX(), getY());
    }

    public void telport() {
        // 目前的功能就只有跟隨前面的單位而已
        // 以後有興趣可能會強化接口以增加功能？
        this.setRefPixelPosition(prev.get2DX(), prev.get2DY());
    }
}
